/**
 * 翻译设置模块
 * 负责管理翻译服务的配置
 */
const TranslationSettings = {
    // API 端点封装
    api: {
        prefix: '/translate/translation-configs',
        getAll: function() {
            return Api.apiRequest(this.prefix);
        },
        create: function(data) {
            return Api.apiRequest(this.prefix, {
                method: 'POST',
                body: JSON.stringify(data)
            });
        },
        update: function(configId, data) {
            return Api.apiRequest(`${this.prefix}/${configId}`, {
                method: 'PUT',
                body: JSON.stringify(data)
            });
        },
        delete: function(configId) {
            return Api.apiRequest(`${this.prefix}/${configId}`, {
                method: 'DELETE'
            });
        },
        setDefault: function(configId) {
            return Api.apiRequest(`${this.prefix}/${configId}/set-default`, {
                method: 'POST'
            });
        },
        toggleShare: function(configId) {
            return Api.apiRequest(`${this.prefix}/${configId}/toggle-share`, {
                method: 'POST'
            });
        }
    },

    // 缓存数据
    data: [],
    
    // 初始化入口
    init: function() {
        // 事件委托，处理弹窗内的各种点击事件
    },

    openModal: async function() {
        try {
            const configs = await this.api.getAll().then(res => {
                // 后端返回的是原始响应，需要判断 data 字段
                const data = res || [];
                this.data = data;
                return data;
            });
            const html = this.renderManagementUI(configs);

            const width = window.innerWidth;
            const isMobileOrTablet = width <= 1400;

            const index = layer.open({
                type: 1,
                title: '翻译设置',
                content: html,
                area: isMobileOrTablet ? ['100%', '100%'] : ['900px', '600px'],
                btn: ['添加配置', '关闭'],
                btnAlign: 'c',
                yes: () => {
                    this.openEditForm();
                    return false;
                },
                success: () => {
                   this.renderTable(configs);
               }
            });
            this.currentLayerIndex = index;

        } catch (error) {
            layer.msg('加载翻译配置失败: ' + error.message, { icon: 2 });
        }
    },

    renderManagementUI: function(configs) {
        // 使用 layui.table.render，只需要一个容器
        return `
            <div style="padding: 15px;">
                <table id="translation-table" lay-filter="translation-table"></table>
            </div>
            <script type="text/html" id="trans-name-tpl">
                {{ d.name }}
                {{# if(d.is_shared && d.is_own){ }}
                    <span style="color: #FFB800; margin-left: 5px;" title="已共享给其他用户">🔗分享</span>
                {{# } else if(!d.is_own) { }}
                    <span style="color: #999; margin-left: 5px;" title="他人共享">🔗共享</span>
                {{# } }}
            </script>
            <script type="text/html" id="trans-status-tpl">
                {{# if(d.is_default){ }}
                    <span class="layui-badge layui-bg-green">默认</span>
                {{# } else { }}
                    <span class="layui-badge layui-bg-gray">非默认</span>
                {{# } }}
            </script>
            <script type="text/html" id="trans-actions-tpl">
                <button class="layui-btn layui-btn-xs" lay-event="set-default" {{ d.is_default ? 'disabled' : '' }}>设为默认</button>
                {{# if(d.is_own){ }}
                    <button class="layui-btn layui-btn-xs" lay-event="copy">复制</button>
                    <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</button>
                    <button class="layui-btn layui-btn-xs {{ d.is_shared ? 'layui-btn-warm' : 'layui-btn-primary' }}" lay-event="toggle-share">{{ d.is_shared ? '取消分享' : '分享' }}</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
                {{# } }}
            </script>
        `;
    },
    
    // 打开编辑/新增表单
    openEditForm: function(config = null) {
        // 通过判断config对象是否有id来确定是编辑还是新增（复制也是一种新增）
        const isEdit = config && config.id;
        const title = isEdit ? '编辑翻译配置' : '添加翻译配置';

        const formHtml = `
            <div id="translation-edit-form" class="layui-form" style="padding: 20px;">
                <div class="layui-form-item">
                    <label class="layui-form-label">配置名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" required lay-verify="required" placeholder="例如：我的百度翻译" autocomplete="off" class="layui-input" value="${config ? escapeHtml(config.name) : ''}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">服务商</label>
                    <div class="layui-input-block">
                        <select name="provider" id="translation-provider-select" lay-filter="translation-provider-select" lay-verify="required" ${isEdit ? 'disabled' : ''}>
                            <option value="">请选择服务商</option>
                            <option value="baidu" ${config ? (config.provider === 'baidu' ? 'selected' : '') : 'selected'}>百度翻译</option>
                            <option value="deeplx" ${config && config.provider === 'deeplx' ? 'selected' : ''}>DeeplX</option>
                            <option value="ai" ${config && config.provider === 'ai' ? 'selected' : ''}>自定义AI</option>
                        </select>
                    </div>
                </div>
                
                <!-- 动态字段区域 -->
                <div id="provider-fields"></div>
            </div>
        `;
        
        layer.open({
            type: 1,
            title: title,
            area: window.innerWidth <= 1400 ? ['100%', '100%'] : ['600px', '580px'],
            content: formHtml,
            btn: ['保存', '取消'],
            success: (layero, index) => {
                layui.form.render('select');
                if (config) {
                    this.toggleProviderFields(config.provider, config.credentials);
                } else {
                    // 新增模式下，默认显示百度翻译的字段
                    this.toggleProviderFields('baidu');
                }
                // 只要不是编辑模式，就允许切换服务商
                if (!isEdit) {
                    layui.form.on('select(translation-provider-select)', (data) => {
                        this.toggleProviderFields(data.value);
                    });
                }
            },
            yes: (index, layero) => {
                this.handleSave(index, isEdit, config ? config.id : null);
            }
        });
    },

    // 切换服务商对应的表单字段
    toggleProviderFields: function(provider, credentials = {}) {
        const container = $('#provider-fields');
        let fieldsHtml = '';

        switch (provider) {
            case 'baidu':
                fieldsHtml = `
                    <div class="layui-form-item">
                        <label class="layui-form-label">App ID</label>
                        <div class="layui-input-block">
                            <input type="text" name="appId" required lay-verify="required" placeholder="请输入App ID" class="layui-input" value="${credentials.appId || ''}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密钥</label>
                        <div class="layui-input-block">
                            <input type="password" name="secretKey" required lay-verify="required" placeholder="请输入密钥" class="layui-input" value="${credentials.secretKey || ''}">
                        </div>
                    </div>
                `;
                break;
            case 'deeplx':
                fieldsHtml = `
                    <div class="layui-form-item">
                        <label class="layui-form-label">URL</label>
                        <div class="layui-input-block">
                            <input type="text" name="url" required lay-verify="required" placeholder="请输入DeeplX API URL" class="layui-input" value="${credentials.url || ''}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">授权密钥</label>
                        <div class="layui-input-block">
                            <input type="password" name="key" placeholder="（可选）请输入授权密钥" class="layui-input" value="${credentials.key || ''}">
                        </div>
                    </div>
                `;
                break;
            case 'ai':
                fieldsHtml = `
                    <div class="layui-form-item">
                        <label class="layui-form-label">API URL</label>
                        <div class="layui-input-block">
                            <input type="text" name="url" id="ai-url-input" required lay-verify="required" placeholder="例如：https://api.openai.com" class="layui-input" value="${credentials.url || ''}">
                            <div class="layui-form-mid layui-word-aux" style="margin-top: 5px;">/ 结尾忽略 v1 版本，# 结尾强制使用输入地址</div>
                            <div id="ai-url-preview" class="layui-form-mid layui-word-aux" style="margin-top: 5px; color: #009688;">实际调用: </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">API Key</label>
                        <div class="layui-input-block">
                            <input type="password" name="key" id="ai-key-input" required lay-verify="required" placeholder="请输入API Key" class="layui-input" value="${credentials.key || ''}">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">模型</label>
                        <div class="layui-input-block">
                            <input type="text" name="model" id="ai-model-input" required lay-verify="required" placeholder="点击获取模型列表或直接输入" class="layui-input" value="${credentials.model || ''}" list="ai-model-datalist" autocomplete="off">
                            <datalist id="ai-model-datalist"></datalist>
                            <div class="layui-form-mid layui-word-aux" style="margin-top: 5px;">点击输入框自动获取模型列表，支持选择或直接输入自定义模型</div>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">提示词</label>
                        <div class="layui-input-block">
                            <textarea name="prompt" placeholder="（可选）自定义提示词，可使用变量：{text_json} {target_language}，留空使用默认提示词" class="layui-textarea" style="min-height: 100px;">${credentials.prompt || ''}</textarea>
                        </div>
                    </div>
                `;
                break;
        }
        container.html(fieldsHtml);
        
        // 渲染新添加的表单元素
        layui.form.render();
        
        // 如果是AI配置，绑定URL实时预览和获取模型事件
        if (provider === 'ai') {
            this.bindAIFieldEvents();
        }
    },
    
    // 绑定AI配置字段的事件
    bindAIFieldEvents: function() {
        const self = this;
        let modelsFetched = false; // 标记是否已获取过模型列表
        let isFetching = false; // 标记是否正在获取
        let lastUrl = ''; // 记录上次的URL
        let lastKey = ''; // 记录上次的Key
        
        // URL实时预览
        const updateUrlPreview = function() {
            const url = $('#ai-url-input').val().trim();
            if (!url) {
                $('#ai-url-preview').text('实际调用: ');
                return;
            }
            
            let processedUrl = url;
            
            // 处理URL规则
            if (url.endsWith('#')) {
                processedUrl = url.slice(0, -1);
            } else if (url.endsWith('/')) {
                processedUrl = url.slice(0, -1) + '/chat/completions';
            } else if (url.endsWith('/v1')) {
                processedUrl = url + '/chat/completions';
            } else {
                processedUrl = url + '/v1/chat/completions';
            }
            
            $('#ai-url-preview').text('实际调用: ' + processedUrl);
        };
        
        // 绑定URL和Key输入框的input事件
        $('#ai-url-input, #ai-key-input').on('input', function() {
            updateUrlPreview();
            // URL或Key变化时重置获取标记
            modelsFetched = false;
        });
        
        // 初始化时更新一次
        updateUrlPreview();
        
        // 模型输入框点击或聚焦时自动获取模型列表
        $('#ai-model-input').on('focus click', function() {
            const url = $('#ai-url-input').val().trim();
            const key = $('#ai-key-input').val().trim();
            
            // 检查URL或Key是否变化
            if (url !== lastUrl || key !== lastKey) {
                modelsFetched = false;
                lastUrl = url;
                lastKey = key;
            }
            
            // 如果已经获取过或正在获取，不再重复
            if (modelsFetched || isFetching) {
                return;
            }
            
            if (!url || !key) {
                return;
            }
            
            // 标记为正在获取
            isFetching = true;
            
            // 更新输入框placeholder
            const input = $(this);
            const originalPlaceholder = input.attr('placeholder');
            input.attr('placeholder', '获取模型列表中...');
            
            // 调用后端API获取模型列表
            Api.apiRequest(`/translate/ai-models?api_url=${encodeURIComponent(url)}&api_key=${encodeURIComponent(key)}`, {
                method: 'POST'
            }).then(models => {
                modelsFetched = true;
                
                if (models && models.length > 0) {
                    // 更新datalist
                    const datalist = $('#ai-model-datalist');
                    datalist.empty();
                    
                    models.forEach(model => {
                        datalist.append(`<option value="${escapeHtml(model)}">`);
                    });
                    
                    input.attr('placeholder', '从列表选择或直接输入模型名称');
                    console.log(`成功获取 ${models.length} 个模型`);
                } else {
                    input.attr('placeholder', '未获取到模型，请直接输入模型名称');
                }
            }).catch(error => {
                console.warn('获取模型列表失败:', error.message);
                input.attr('placeholder', '获取失败，请直接输入模型名称');
            }).finally(() => {
                isFetching = false;
            });
        });
    },

    // 处理保存
    handleSave: function(layerIndex, isEdit, configId) {
        const form = $('#translation-edit-form');
        const name = form.find('input[name="name"]').val().trim();
        const provider = form.find('select[name="provider"]').val();
        
        if (!name) {
            return layer.msg('配置名称不能为空', { icon: 2 });
        }
        if (!provider) {
            return layer.msg('请选择服务商', { icon: 2 });
        }
        
        let credentials = {};
        switch (provider) {
            case 'baidu':
                credentials.appId = form.find('input[name="appId"]').val().trim();
                credentials.secretKey = form.find('input[name="secretKey"]').val().trim();
                if (!credentials.appId || !credentials.secretKey) return layer.msg('App ID和密钥不能为空', { icon: 2 });
                break;
            case 'deeplx':
                credentials.url = form.find('input[name="url"]').val().trim();
                credentials.key = form.find('input[name="key"]').val().trim();
                if (!credentials.url) return layer.msg('URL不能为空', { icon: 2 });
                break;
            case 'ai':
                credentials.url = form.find('input[name="url"]').val().trim();
                credentials.key = form.find('input[name="key"]').val().trim();
                credentials.model = form.find('input[name="model"]').val().trim();
                credentials.prompt = form.find('textarea[name="prompt"]').val().trim();
                if (!credentials.url || !credentials.key || !credentials.model) return layer.msg('URL、Key和模型不能为空', { icon: 2 });
                break;
        }

        const data = { name, provider, credentials };
        
        const apiCall = isEdit ? this.api.update(configId, data) : this.api.create(data);
        
        apiCall.then(res => {
            layer.msg('操作成功', { icon: 1 });
            layer.close(layerIndex);
            this.refreshList();
        }).catch(error => {
            layer.msg('操作失败: ' + error.message, { icon: 2 });
        });
    },

    // 处理删除
    handleDelete: function(configId) {
        layer.confirm('确定要删除此配置吗？', { icon: 3, title: '确认删除' }, (index) => {
            layer.close(index);
            this.api.delete(configId).then(res => {
                layer.msg('删除成功', { icon: 1 });
                this.refreshList();
            }).catch(error => {
                layer.msg('删除失败: ' + error.message, { icon: 2 });
            });
        });
    },

    // 处理设置默认
    handleSetDefault: function(configId) {
        this.api.setDefault(configId).then(res => {
            layer.msg('设置成功', { icon: 1 });
            this.refreshList();
        }).catch(error => {
            layer.msg('设置失败: ' + error.message, { icon: 2 });
        });
    },

    handleToggleShare: function(configId) {
        this.api.toggleShare(configId).then(res => {
            layer.msg(res.msg || '操作成功', { icon: 1 });
            this.refreshList();
        }).catch(error => {
            layer.msg('操作失败: ' + error.message, { icon: 2 });
        });
    },

    bindEvents: function() {
        // 使用事件委托来处理动态生成的按钮
        $('.layui-layer-content').off('click').on('click', 'button[data-action]', (e) => {
            const action = $(e.currentTarget).data('action');
            const id = $(e.currentTarget).data('id');
            
            switch (action) {
                case 'edit':
                    const config = this.data.find(c => c.id === id);
                    this.openEditForm(config);
                    break;
                case 'copy':
                    const configToCopy = this.data.find(c => c.id === id);
                    if (configToCopy) {
                        // 创建一个副本，移除id，并修改名称
                        const copiedConfig = { ...configToCopy };
                        delete copiedConfig.id;
                        delete copiedConfig.is_default;
                        copiedConfig.name = copiedConfig.name + ' (副本)';
                        this.openEditForm(copiedConfig);
                    }
                    break;
                case 'delete':
                    this.handleDelete(id);
                    break;
                case 'set-default':
                    this.handleSetDefault(id);
                    break;
                case 'toggle-share':
                    this.handleToggleShare(id);
                    break;
            }
        });
    },
    
    refreshList: async function() {
        try {
            const configs = await this.api.getAll().then(res => res || []);
            this.data = configs; // 更新缓存

            if (this.translationTableInstance) {
                this.translationTableInstance.reload({
                    data: this.prepareTableData(configs)
                });
            } else {
                if (!this.currentLayerIndex) {
                    this.openModal();
                } else {
                    const layerElement = $('#layui-layer' + this.currentLayerIndex);
                    if (layerElement.length) {
                        const html = this.renderManagementUI(configs);
                        layerElement.find('.layui-layer-content').html(html);
                        this.renderTable(configs);
                    } else {
                        this.openModal();
                    }
                }
            }
        } catch (error) {
            layer.msg('刷新列表失败: ' + error.message, { icon: 2 });
        }
    },
    
    /**
     * 准备表格所需的数据格式
     */
    prepareTableData: function(configs) {
        const currentUserId = Api.getCurrentUserId();
        const providerMap = {
            baidu: '百度翻译',
            deeplx: 'DeeplX',
            ai: '自定义AI'
        };
        return configs.map(c => ({
            ...c,
            is_own: c.user_id === currentUserId,
            provider_name: providerMap[c.provider] || '未知'
        }));
    },
    
    /**
     * 渲染layui表格
     */
    renderTable: function(configs) {
        const tableData = this.prepareTableData(configs);
        
        this.translationTableInstance = layui.table.render({
            elem: '#translation-table',
            data: tableData,
            cols: [[
                { field: 'name', title: '配置名称', templet: '#trans-name-tpl', minWidth: 200 },
                { field: 'provider_name', title: '服务商', align: 'center' },
                { field: 'is_default', title: '状态', templet: '#trans-status-tpl', width: 100, align: 'center' },
                { title: '操作', templet: '#trans-actions-tpl', align: 'center', fixed: 'right', width: 320 }
            ]],
            skin: 'line',
            limit: configs.length
        });

        // 绑定表格事件
        layui.table.on('tool(translation-table)', (obj) => {
            const data = obj.data;
            const event = obj.event;
            
            switch(event) {
                case 'set-default':
                    this.handleSetDefault(data.id);
                    break;
                case 'copy':
                    const configToCopy = this.data.find(c => c.id === data.id);
                    if (configToCopy) {
                        const copiedConfig = { ...configToCopy };
                        delete copiedConfig.id;
                        delete copiedConfig.is_default;
                        delete copiedConfig.is_shared;
                        copiedConfig.name = copiedConfig.name + ' (副本)';
                        this.openEditForm(copiedConfig);
                    }
                    break;
                case 'edit':
                    this.openEditForm(data);
                    break;
                case 'toggle-share':
                    this.handleToggleShare(data.id);
                    break;
                case 'delete':
                    this.handleDelete(data.id);
                    break;
            }
        });
    }
};

// 初始化
$(function() {
    // TranslationSettings.init(); // 不再需要，因为事件是动态绑定的
});